package com.monitor.util;

import com.monitor.constant.URIPatternConstant;
import com.monitor.model.URLPattenEntity;
import com.monitor.service.URLPatternService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class URIPatternUtil {
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Autowired
    private URLPatternService urlPatternService;

    @PostConstruct
    public void init() {
        // 查询配置
        List<URLPattenEntity> urlPatterns = urlPatternService.list();
        Set<String> uriPatterns = urlPatterns.stream().map(URLPattenEntity::getUriPatten).collect(Collectors.toSet());
        SimpleCache.getSimpleCache().put(URIPatternConstant.URI_PATTERN, uriPatterns);
    }

    public String lookupBestURI(String url) {
        String uri = getUri(url);
        // 获取配置的URIPattern
        Object o = SimpleCache.getSimpleCache().get(URIPatternConstant.URI_PATTERN);
        Set<String> uriPatterns = (Set<String>) o;
        // 完全匹配
        if (uriPatterns.stream().anyMatch(uriPattern -> uriPattern.equals(uri))) {
            return uriPatterns.stream().filter(uriPattern -> uriPattern.equals(uri)).findFirst().orElse("");
        } else {
            // pattern匹配
            return uriPatterns.stream().filter(uriPattern -> antPathMatcher.match(uriPattern, uri)).min(antPathMatcher.getPatternComparator(uri)).orElse("");
        }
    }

    private String getUri(String url) {
        int index = url.indexOf("?");
        if (index != -1) {
            return url.substring(0, index);
        } else {
            return url;
        }
    }

    public String normalize(String url) {
        int index = url.indexOf("?");
        if (index != -1) {
            String param = url.substring(index);
            param.split("");
        }
        return url;
    }

    public static void main(String[] args) {
        Set<String> patterns = new HashSet<>();
//        patterns.add("/km/review/submit/method=add");
        patterns.add("/km/review/{id}/method={m}&{name}={a}");
        patterns.add("/km/review/*?*=*");
        patterns.add("/km/*/*?*=*");
        SimpleCache.getSimpleCache().put(URIPatternConstant.URI_PATTERN, patterns);
//        String url = "/km/review/submit?method=add";
        String url = "/km/review/submit/name=aa&method=add";
        URIPatternUtil uriPatternUtil = new URIPatternUtil();
        System.out.println(uriPatternUtil.lookupBestURI(url));
    }
}
